package com.bigfans.catalogservice.api;

import com.bigfans.catalogservice.model.Category;
import com.bigfans.catalogservice.model.Product;
import com.bigfans.catalogservice.service.attribute.AttributeOptionService;
import com.bigfans.catalogservice.service.category.CategoryService;
import com.bigfans.catalogservice.service.product.ProductService;
import com.bigfans.framework.annotations.NeedLogin;
import com.bigfans.framework.web.RestResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
public class CategoryApi {

	private AttributeOptionService attributeService;

	@Autowired
	private CategoryService categoryService;
	@Autowired
	private ProductService productService;

	@GetMapping(value = "/navigator")
	public RestResponse navigator() throws Exception{
		List<Category> productCatList = categoryService.getNavigatorTree();
		return RestResponse.ok(productCatList);
	}

	@GetMapping(value = "/crumbs")
	public RestResponse crumbs(
			@RequestParam(value = "catId" , required = false) String catId,
			@RequestParam(value = "prodId" , required = false) String prodId
	) throws Exception{
		List<Category> categoryCrumbs = new ArrayList<>();
		if(catId != null){
			Category currentCategory = categoryService.loadParents(catId);
			categoryCrumbs = currentCategory.toCrumbs();
		} else if (prodId != null) {
			Product prod = productService.load(prodId);
			Category currentCategory = categoryService.loadParents(prod.getCategoryId());
			categoryCrumbs = currentCategory.toCrumbs();
			Map<String , Object> result = new HashMap<>();
			result.put("prodName" , prod.getName());
			result.put("crumbs" , categoryCrumbs);
			return RestResponse.ok(result);
		}
		return RestResponse.ok(categoryCrumbs);
	}

	@GetMapping(value = "/subcats")
	@NeedLogin
	public RestResponse listsubs(
			@RequestParam(value = "pid") String parentId
	) throws Exception{
		List<Category> subcats = categoryService.listSubCats(parentId);
		Map<String , Object> data = new HashMap<>();
		data.put("subcats" , subcats);
		return RestResponse.ok(data);
	}
}
